<!-- 商品列表组件 -->
<!-- 商品列表组件 -->
<template>
  <div>
    <div class="infinite-list-wrapper" style="overflow:auto">
      <ul
        class="list"
        v-infinite-scroll="load"
        infinite-scroll-disabled="disabled">
        <li 
          v-for="item in visibleItems" 
          :key="item.product_id" 
          class="list-item"
          @click="goToProductDetail(item.product_id)">
          <div class="popularimg">
            <img :src="getImageUrl(item.image)"  @error="handleImageError"  alt="" />
          </div>
          <div>
            {{item.name}}
          </div>
          <div class="price-goods">{{item.price}}元起</div>
        </li>
      </ul>
      <p v-if="loading">加载中...</p>
      <p v-if="noMore && visibleItems.length > 0" class="nomore">没有更多了!</p>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request.js'
export default {
  data() {
    return {
      shopgoodslist: [],    // 所有商品数据
      visibleItems: [],      // 当前显示的数据
      loading: false,        // 加载状态
      currentPage: 0,        // 当前页码
      itemsPerLoad: 9,       // 每次加载数量
      totalItems: 0,         // 总数据量
      hasError: false        // 是否发生错误
    }
  },
  computed: {
    noMore() {
      return this.visibleItems.length >= this.totalItems
    },
    disabled() {
      return this.loading || this.noMore || this.hasError
    }
  },
  created() {
    this.fetchAllData()
  },
  methods: {
    getImageUrl(relativePath){
      return require(`@/assets/img/goods/${relativePath}`); 
    },
    // 图片加载失败处理
    handleImageError(e) {
      e.target.src = require("../assets/img/goods/dian-1.png"); // 默认图片
    },
    // 跳转到商品详情页
    goToProductDetail(productId) {
		 console.log("商品ID:", productId); // 检查是否打印出正确的ID
		  if (!productId) {
		    console.error("商品ID不存在", this.visibleItems); // 打印当前数据检查结构
		    return;
		  }
		  this.$router.push(`/product/${productId}`);
    },
	// 查询所有商品
    fetchAllData() {
      this.loading = true
      request.get('/products/allproducts')
        .then(res => {
          if (res.code === '200') {
            this.shopgoodslist = res.data || []
            this.totalItems = this.shopgoodslist.length
            // 初始加载第一页数据
            this.loadInitialData()
          }
        })
        .catch(error => {
          console.error('获取商品列表失败:', error)
          this.hasError = true
        })
        .finally(() => {
          this.loading = false
        })
    },
    loadInitialData() {
      const end = Math.min(this.itemsPerLoad, this.totalItems)
      this.visibleItems = this.shopgoodslist.slice(0, end)
      this.currentPage = 1
    },
    load() {
      if (this.disabled) return
      
      this.loading = true
      setTimeout(() => {
        const start = this.currentPage * this.itemsPerLoad
        const end = start + this.itemsPerLoad
        const newItems = this.shopgoodslist.slice(start, end)
        
        this.visibleItems = [...this.visibleItems, ...newItems]
        this.currentPage++
        this.loading = false
      }, 500)
    }
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */

.price-goods{
  color: red;
  padding-bottom: 30px;
}
.list {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -5px;
  padding: 0;
  list-style: none;
}

.list-item {
  width: calc(20% - 10px);
  margin: 0 5px 10px;
  box-sizing: border-box;
  text-align: center;
  transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
  cursor: pointer;
}
li.list-item:hover {
transform: translateY(-10px);
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.popularimg img {
  width: 100%;
  height: auto;
  max-height: 160px;
  object-fit: contain;
  padding-top: 30px;
}

.product-name {
  margin-top: 8px;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.nomore{
  text-align: center;
}
</style>